//
//  LXCarOrderDetailViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2022/2/15.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXCarOrderDetailViewController.h"
#import "LXSignContractModel.h"
#import "LXCarOrderModel.h"
#import "LXCarOrederTableViewCell.h"
#import "LXCarOrderApplyViewController.h"
#import "LXSignContractApplyViewController.h"
@interface LXCarOrderDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSInteger selectIndex;
@property (nonatomic) NSDictionary *carInfo;
@property (nonatomic) NSInteger pageIndex,rows;
@end

@implementation LXCarOrderDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self layoutCustomNav:self.view title:@"下定详情"];
    self.pageIndex = 1;
    // 当前不选中cell
    self.selectIndex = -1;
    // 每页十条
    self.rows = 10;
    
    [self.view addSubview:self.tableView];

    
    [self loadData];
    
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
         self.pageIndex++;
        [self loadData];
    }];
    

    
    [self setBottomViewWithText:@"签约"];


}

- (void)loadData{
    
   
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    NSString *url = [DOMAIN_URL stringByAppendingFormat:TBookingPage_URL,self.orderModel.carId,@(self.pageIndex),@(self.rows)];
    
    [MSNetworkManager getRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        [self endRefreshing];
        
        if (isSuccess) {
            
            // 车辆信息
            NSDictionary *carInfo = resonseObj[@"carInfo"];
            self.carInfo = carInfo;
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:carInfo];
            [dic setValue:resonseObj[@"bookingCount"] forKey:@"bookingCount"];
            self.tableView.tableHeaderView = [self setTableHeaderView:dic];
            
            // 预约人
            NSArray *records = resonseObj[@"page"][@"records"];
            [self.data addObjectsFromArray:[LXSignContractModel  mj_objectArrayWithKeyValuesArray:records]];
        

            NSInteger totalPage = [resonseObj[@"page"][@"total"] integerValue];


            if (self.data.count>=totalPage) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
            }
            
          
            [self.tableView reloadData];
        }
        [self isHaveEmptyData];
       
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self isHaveEmptyData];
    } withShowHud:YES];
    
    
}

- (UIView *)setTableHeaderView:(NSDictionary *)dic{
    
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 140)];
    headV.backgroundColor = [UIColor whiteColor];
    
    UILabel *carNum = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, ScreenWidth - 40, 22)];
    carNum.text = [NSString stringWithNull:dic[@"brand"]];
    carNum.font = [UIFont boldSystemFontOfSize:20];
    [headV addSubview:carNum];
    
    UILabel *carBrand = [[UILabel alloc] initWithFrame:CGRectMake(20, MaxY(carNum)+5, ScreenWidth - 40, 22)];
    carBrand.text = [NSString stringWithNull:dic[@"model"]];
    carBrand.font = [UIFont boldSystemFontOfSize:12];
    carBrand.textColor = [UIColor colorWithHexString:@"#999999"];
    [headV addSubview:carBrand];
    
    
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(20, MaxY(carBrand)+8, ScreenWidth - 40, 22)];
    line.text = @"------------------------------------------------------------------------------------------------------------";
    line.font = [UIFont systemFontOfSize:9];
    line.lineBreakMode = NSLineBreakByClipping;
    line.textColor = [UIColor colorWithHexString:@"#F1F1F1"];
    [headV addSubview:line];
    
    
    
    UILabel *contact = [[UILabel alloc] initWithFrame:CGRectMake(20, MaxY(line)+8, ScreenWidth - 40, 22)];
    contact.text = @"下定联系人 选择一个联系人签约";
    contact.font = [UIFont boldSystemFontOfSize:16];
    contact.textColor = [UIColor colorWithHexString:@"#333333"];
    [headV addSubview:contact];
    
    [contact addAttributes:TextAttrCorlor(ColorWithAAAAAA) forString:@"选择一个联系人签约" size:12];
    
    
    UILabel *bookingCount = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 200, MaxY(line)+13, ScreenWidth - 225, 22)];
    bookingCount.textAlignment = NSTextAlignmentRight;
    bookingCount.text =  [NSString stringWithFormat:@"%@人已预订",!StringIsEmpty(dic[@"bookingCount"])?dic[@"bookingCount"]:@"0"];
    bookingCount.font = [UIFont boldSystemFontOfSize:12];
    bookingCount.textColor = [UIColor colorWithHexString:@"#EA545A"];
    [headV addSubview:bookingCount];
    
    
    
    
    
    
    return headV;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LXSignContractModel *model = self.data[indexPath.row];

    static NSString *identifier = @"cell2";

    LXCarOrederTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LXCarOrederTableViewCell class]) owner:self options:nil] objectAtIndex:1];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
  
    
    cell.userNameLbCell2.text = [NSString stringWithNull:model.username];
    cell.userPhoneLbCell2.text = [NSString stringWithNull:model.phone];
    cell.timeLbCell2.text = [NSString stringWithNull:model.createTime];
    
    
    [cell.callPhoneBtn whenTapped:^{
    
        [NSString callPhone:model.phone];

    }];
    
    if(self.selectIndex==indexPath.row||self.data.count==1){
        self.selectIndex = indexPath.row;
        [cell.backViewCell2 createBordersWithColor:mainColor withCornerRadius:5 andWidth:1];
        cell.backViewCell2.backgroundColor = UIColor.whiteColor;
    }
    else {
        [cell.backViewCell2 createBordersWithColor:[UIColor clearColor] withCornerRadius:5 andWidth:0];
        cell.backViewCell2.backgroundColor = ColorWithF5F5F5;
    }
    
    return cell;
    

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    // 记录选中的cell
    self.selectIndex = indexPath.row;
    
    [self.tableView reloadData];
    
}


- (void)clickBottomView:(UIButton *)sender{
    
    
    if (self.selectIndex == -1){
        showAlert(@"请先选择签约人");
        return;
    }
    
//    LXCarOrderModel *model = self.data[self.selectIndex];
//    LXCarOrderApplyViewController *vc = [[LXCarOrderApplyViewController alloc] init];
//    vc.orderModel = model;
//    vc.type = 1;
//    [self pushToNextController:vc];
    
    LXSignContractModel *model = self.data[self.selectIndex];
    LXSignContractApplyViewController *vc = [[LXSignContractApplyViewController alloc] init];
    vc.type = 2;
    
    
    LXSignContractModel *signContractModel = [LXSignContractModel new];
    signContractModel.carId = self.carInfo[@"id"];
    signContractModel.signCarBrand = self.carInfo[@"brand"];
    signContractModel.signModel = self.carInfo[@"model"];
    signContractModel.driverId = model.driverId;
    signContractModel.driverName = model.username;
    signContractModel.driverPhone = model.phone;
    signContractModel.bookingId = model.ID;
    vc.signContractModel = signContractModel;
    vc.fromVC = @"LXCarOerderRecordViewController";
    [self pushToNextController:vc];

    
}


- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, ScreenWidth, kScreenHeight - LL_StatusBarAndNavigationBarHeight - kComHeight - 15) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 80;
        
    }
    return _tableView;
}

- (void)isHaveEmptyData{
    if (self.data.count == 0) {
        self.tableView.startTip = YES;
        self.tableView.tipView.backgroundColor = self.tableView.backgroundColor;
        self.tableView.tipImage = [UIImage imageNamed:@"No_order_icon"];
        self.tableView.tipView.hidden = NO;
        self.tableView.scrollEnabled = YES;
    }else{
        self.tableView.tipView.hidden = YES;
        self.tableView.scrollEnabled = YES;
    }
}

- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}
@end
